package com.chat.chatter.server;

import java.util.List;

import javax.persistence.EntityManager;

import com.chat.chatter.client.GreetingService;
import com.chat.chatter.ejb.Emf;
import com.chat.chatter.ejb.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) {
		//my try
		EntityManager em = Emf.get().createEntityManager();
		
		User user = new User();
		user.setName(input);
		user.setUsername(input);
		user.setPassword("password");		
		String doesItExist = "does not exist.";
		
		try {
	        // ... do stuff with em ...
			if ( null == em ) {
                System.out.println( "entityManagerFactory is hosed" );
			}
			
			System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + user.getUsername());
		    List existing = em.createQuery(
		         "select u.username from User u where u.username = :username")
		         .setParameter("username", user.getUsername())
		         .getResultList();

		    if ( existing.size() == 0 ) {
		    	System.out.println("!!!DOES NOT EXIST, CREATING!!!");
		        //entityManager.persist(user);
		        em.persist(user);
		        //log.info("Registered new user #{user.username}");
		        //return "/registered.xhtml";
		        System.out.println("created");
		    }
		    else {
		    	System.out.println("Users");
		    	//for (User u : existing ) {
		    		System.out.println(existing);
		    	//}
		    	System.out.println("!!!EXISTS, NOT CREATING!!!");
		    	doesItExist = "exists";
		        //return null;
		    }
	    } finally {
	        em.close();
	    }
	    
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent
				+ "<br><br>User, " + user.getUsername() + " " + doesItExist;
	}
}
